package com.jcp.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class JcpFilter
 */
@WebFilter(urlPatterns = "/*")
public class JcpFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public JcpFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		if (request.getSession().getAttribute("user") != null) {
			// pass the request along the filter chain
			chain.doFilter(req, res);
		} else {
			//System.out.println("request.getRequestURI() :" + request.getRequestURI());

			String op = "";
			if (request.getParameter("op") != null) {
				op = request.getParameter("op");
			}
			// jsp html .css .js .jpg ....
			// 戴布斯：移除打卡过滤
			if (request.getRequestURI().endsWith(".json") || request.getRequestURI().endsWith("loginservlet")
					|| request.getRequestURI().endsWith("login.jsp") || request.getRequestURI().endsWith("clock.jsp")
					|| request.getRequestURI().endsWith(".css") || request.getRequestURI().endsWith(".js")
					|| request.getRequestURI().endsWith(".jpg") || request.getRequestURI().endsWith(".png")
					|| request.getRequestURI().endsWith(".gif") || op.equals("login") || op.equals("clock")) {
				chain.doFilter(req, res);
			} else {
				// 跳转到登录页面去
				response.sendRedirect("login.jsp");

			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
